import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/income_invoice_entity.dart';

import '../../../constants.dart';
import '../../../models/income_order_list_entity.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class OrderIncomeLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var orderListEntity = Rxn<IncomeOrderListEntity>();
  var isLoading = true.obs;
  var isSearching = false.obs;
  var isSearched = false.obs;
  var bottomTips = ''.obs;
  var orderList = <IncomeOrderInfo>[].obs;
  var status = 0.obs;

  late TabController tabController;
  late ScrollController scrollController;
  late TextEditingController searchController;

  final pageSize = 20;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();

    tabController =
        TabController(length: incomeOrderStatus.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        status.value = tabController.index;
        reload();
      }
    });

    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getOrders(status.value);
      }
    });

    searchController = TextEditingController();

    reload();
  }

  void onClickSearch() {
    isSearching.value = true;
    isSearched.value = false;
  }

  void onCancelSearch() {
    isSearching.value = false;
    isSearched.value = false;
    searchController.clear();
  }

  void onSearch() {
    if (searchController.text.isNotEmpty) {
      _page = 1;
      orderList.clear();
      isLoading.value = true;
      _getOrders(status.value);
    }
  }

  void toOrderDetail(int index) async {
    var result = await Get.toNamed(RouteGet.incomeOrderDetail,
        arguments: orderList[index]);

    if (result != null && result as bool == true) {
      reload();
    }
  }

  void toCreateOrder() async {
    var result = await Get.toNamed(RouteGet.incomeOrderCreate);

    if (result != null && result as bool == true) {
      reload();
    }
  }

  String invoiceStatus(IncomeOrderInfo item) {
    final status = item.invoiceStatus;
    if (status == 0) {
      if (item.invoice == null || item.invoice!.isEmpty) {
        return '发票未填';
      }
      final invoiceEntity =
          IncomeInvoiceEntity.fromJson(jsonDecode(item.invoice ?? '{}'));
      if (invoiceEntity.taxid != null && invoiceEntity.taxid!.isNotEmpty) {
        return '发票已填未开出';
      }
      return '发票未填';
    } else if (status == 1) {
      return '已开发票';
    } else if (status == 2) {
      return '发票作废';
    } else if (status == 3) {
      return '不开发票';
    } else if (status == 4) {
      return '自动开票中';
    } else if (status == 5) {
      return '自动开票错误';
    } else if (status == 6) {
      return '已自动开票';
    } else {
      return '未知状态';
    }
  }

  @override
  void onClose() {
    tabController.dispose();
    scrollController.dispose();
    super.onClose();
  }

  void reload() {
    _page = 1;
    orderList.clear();
    isLoading.value = true;
    isSearched.value = false;
    isSearching.value = false;
    _getOrders(status.value);
  }

  void _getOrders(int status) {
    apiService
        .getIncomeOrders(
          page: _page,
          pageSize: pageSize,
          role: commonService.getRole(),
          status: status == 0 ? null : status - 1,
          name: isSearching.value ? searchController.text : '',
        )
        .then((orders) => {
              isLoading.value = false,
              isSearched.value = true,
              _page++,
              if (orders != null)
                {
                  orderListEntity.value = orders,
                  if (orders.data != null && orders.data!.isNotEmpty)
                    {orderList.addAll(orders.data ?? [])},
                  if (orders.data!.length < pageSize)
                    {bottomTips.value = noMoreTip}
                  else
                    {bottomTips.value = loadingTip}
                }
              else
                {bottomTips.value = noMoreTip},
            });
  }
}
